<template>
  <div class="pos-container">
    <!-- 顶部工具栏 -->
    <div class="pos-header">
      <div class="logo-section">
        <img src="/src/assets/logo.png" class="logo-image" alt="银杏ERP" />
        <span class="logo-text">银杏ERP | POS零售台</span>
      </div>
      <div class="action-section">
        <el-button-group>
          <el-button type="primary" @click="newOrder">
            <el-icon><Document /></el-icon> 新订单
          </el-button>
          <el-button type="info" @click="showOrderHistory">
            <el-icon><Clock /></el-icon> 历史订单
          </el-button>
        </el-button-group>
        
        <el-input
          v-model="searchQuery"
          placeholder="搜索商品/条码"
          clearable
          class="search-input"
          @keyup.enter="searchProduct"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
          <template #append>
            <el-button @click="handleScanCode">
              <el-icon><ScanningFilled /></el-icon>
            </el-button>
          </template>
        </el-input>

        <el-select 
          v-model="selectedStore" 
          placeholder="选择店铺"
          class="store-select"
        >
          <el-option
            v-for="item in stores"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>

        <div class="cashier-info">
          <el-icon><User /></el-icon>
          <span>{{ cashierName }}</span>
        </div>
        
        <el-button type="warning" @click="showShiftChangeDialog">
          <el-icon><SwitchFilled /></el-icon> 交班
        </el-button>
      </div>
    </div>

    <div class="pos-content">
      <!-- 左侧商品区 -->
      <div class="pos-left-panel">
        <!-- 分类导航 -->
        <product-categories 
          :categories="categories" 
          :active-category="activeCategory"
          @category-change="changeCategory"
        />
        
        <!-- 商品列表 -->
        <product-list 
          :products="filteredProducts" 
          :loading="productsLoading"
          @add-to-cart="addToCart"
        />
      </div>

      <!-- 右侧购物车和结算区 -->
      <div class="pos-right-panel">
        <!-- 购物车和结算信息 -->
        <shopping-cart 
          :cart-items="cartItems" 
          :customer="customer"
          :total-amount="totalAmount"
          :discount-amount="discountAmount"
          :payable-amount="payableAmount"
          @update-quantity="updateCartItemQuantity"
          @remove-item="removeCartItem"
          @select-customer="selectCustomer"
          @apply-discount="applyDiscount"
          @clear-cart="clearCart"
        />
        
        <!-- 支付操作区 -->
        <payment-section 
          :payable-amount="payableAmount"
          :payment-methods="paymentMethods"
          @complete-payment="completePayment"
          @scan-coupon="handleScanCoupon"
          @round-down="applyRoundDown"
          @manual-discount="showManualDiscountDialog"
        />
      </div>
    </div>

    <!-- 订单历史对话框 -->
    <order-history-dialog
      v-model="orderHistoryVisible"
      @select-order="loadOrder"
    />

    <!-- 客户选择对话框 -->
    <customer-select-dialog
      v-model="customerSelectVisible"
      @select-customer="onCustomerSelected"
    />

    <!-- 支付完成对话框 -->
    <payment-complete-dialog
      v-model="paymentCompleteVisible"
      :order-info="completedOrderInfo"
      @print-receipt="printReceipt"
      @continue-shopping="startNewOrder"
    />
    
    <!-- 扫码对话框 -->
    <el-dialog
      v-model="scanDialogVisible"
      title="扫码"
      width="400px"
      destroy-on-close
    >
      <div class="scan-dialog-content">
        <div class="scan-type-tabs">
          <el-radio-group v-model="scanType" size="large">
            <el-radio-button label="product">商品条码</el-radio-button>
            <el-radio-button label="coupon">优惠券</el-radio-button>
            <el-radio-button label="verification">核销码</el-radio-button>
          </el-radio-group>
        </div>
        
        <div class="scan-input-area">
          <el-input
            v-model="scanCode"
            autofocus
            placeholder="请扫描条码或二维码"
            @keyup.enter="processScanCode"
          >
            <template #append>
              <el-button @click="processScanCode">确认</el-button>
            </template>
          </el-input>
          
          <div class="scan-tip">
            <el-icon><Connection /></el-icon>
            <span>{{ getScanTypeTip() }}</span>
          </div>
        </div>
      </div>
    </el-dialog>
    
    <!-- 交班对话框 -->
    <el-dialog
      v-model="shiftChangeVisible"
      title="交班结算"
      width="500px"
      destroy-on-close
    >
      <div class="shift-change-content">
        <div class="shift-info">
          <div class="shift-header">
            <div class="cashier-name">{{ cashierName }} ({{ selectedStore }})</div>
            <div class="shift-time">
              <div>开始时间: {{ shiftStartTime }}</div>
              <div>结束时间: {{ getCurrentTime() }}</div>
            </div>
          </div>
          
          <el-divider />
          
          <div class="shift-summary">
            <div class="summary-item">
              <span class="item-label">订单总数:</span>
              <span class="item-value">{{ shiftSummary.orderCount }} 笔</span>
            </div>
            <div class="summary-item">
              <span class="item-label">销售总额:</span>
              <span class="item-value">¥{{ formatPrice(shiftSummary.totalSales) }}</span>
            </div>
            <div class="summary-item">
              <span class="item-label">折扣总额:</span>
              <span class="item-value">¥{{ formatPrice(shiftSummary.totalDiscount) }}</span>
            </div>
            <div class="summary-item">
              <span class="item-label">退款总额:</span>
              <span class="item-value">¥{{ formatPrice(shiftSummary.totalRefund) }}</span>
            </div>
            
            <el-divider />
            
            <div class="payment-breakdown">
              <div class="breakdown-title">支付方式明细</div>
              <div 
                v-for="(amount, method) in shiftSummary.paymentBreakdown" 
                :key="method"
                class="breakdown-item"
              >
                <span class="item-label">{{ getPaymentMethodName(method) }}:</span>
                <span class="item-value">¥{{ formatPrice(amount) }}</span>
              </div>
            </div>
          </div>
          
          <el-divider />
          
          <div class="handover-info">
            <div class="handover-title">交班信息</div>
            
            <div class="handover-form">
              <el-form :model="handoverForm" label-width="80px" label-position="left">
                <el-form-item label="交班类型">
                  <el-radio-group v-model="handoverForm.type">
                    <el-radio-button label="shift">班次交接</el-radio-button>
                    <el-radio-button label="daily">日结</el-radio-button>
                  </el-radio-group>
                </el-form-item>
                
                <el-form-item label="交接人">
                  <el-select v-model="handoverForm.nextCashier" placeholder="选择交接收银员">
                    <el-option
                      v-for="cashier in availableCashiers"
                      :key="cashier.id"
                      :label="cashier.name"
                      :value="cashier.id"
                    ></el-option>
                  </el-select>
                </el-form-item>
                
                <el-form-item label="操作密码" v-if="handoverForm.type === 'daily'">
                  <el-input 
                    v-model="handoverForm.password"
                    type="password" 
                    placeholder="请输入管理员密码"
                  ></el-input>
                </el-form-item>
                
                <el-form-item label="备注">
                  <el-input 
                    v-model="handoverForm.remark"
                    type="textarea" 
                    :rows="2"
                    placeholder="交班备注信息"
                  ></el-input>
                </el-form-item>
              </el-form>
            </div>
          </div>
        </div>
        
        <div class="shift-actions">
          <el-button @click="shiftChangeVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmShiftChange">确认交班</el-button>
          <el-button type="success" @click="printShiftSummary">
            <el-icon><Printer /></el-icon> 打印汇总
          </el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script lang="ts">
import { defineComponent, ref, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import ProductCategories from './components/ProductCategories.vue'
import ProductList from './components/ProductList.vue'
import ShoppingCart from './components/ShoppingCart.vue'
import PaymentSection from './components/PaymentSection.vue'
import OrderHistoryDialog from './components/OrderHistoryDialog.vue'
import CustomerSelectDialog from './components/CustomerSelectDialog.vue'
import PaymentCompleteDialog from './components/PaymentCompleteDialog.vue'

interface Product {
  id: number;
  name: string;
  code: string;
  price: number;
  image: string;
  inventory: number;
  categoryId: number;
}

interface Category {
  id: number;
  name: string;
  icon: string;
}

interface CartItem {
  id: number;
  productId: number;
  name: string;
  price: number;
  originalPrice: number;
  quantity: number;
  image: string;
}

interface Customer {
  id: number;
  name: string;
  phone: string;
  level: string;
  discount: number;
  points: number;
}

interface PaymentMethod {
  id: string;
  name: string;
  icon: string;
}

interface OrderInfo {
  orderNo: string;
  totalAmount: number;
  paidAmount: number;
  change: number;
  paymentMethod: string;
  createTime: string;
}

interface Coupon {
  code: string;
  type: 'fixed' | 'percentage';
  value: number;
  minAmount: number;
  expiryDate: string;
  description: string;
}

interface ShiftSummary {
  orderCount: number;
  totalSales: number;
  totalDiscount: number;
  totalRefund: number;
  paymentBreakdown: Record<string, number>;
}

interface HandoverForm {
  type: 'shift' | 'daily';
  nextCashier: string;
  password: string;
  remark: string;
}

interface Cashier {
  id: string;
  name: string;
}

export default defineComponent({
  name: 'PosRetail',
  components: {
    ProductCategories,
    ProductList,
    ShoppingCart,
    PaymentSection,
    OrderHistoryDialog,
    CustomerSelectDialog,
    PaymentCompleteDialog
  },
  setup() {
    // 搜索和选择店铺
    const searchQuery = ref('')
    const selectedStore = ref('main-store')
    const cashierName = ref('张店长')
    
    // 店铺列表
    const stores = ref([
      { value: 'main-store', label: '总店' },
      { value: 'branch-1', label: '分店1' },
      { value: 'branch-2', label: '分店2' }
    ])
    
    // 分类和商品
    const categories = ref<Category[]>([
      { id: 0, name: '全部', icon: 'fa fa-th-large' },
      { id: 1, name: '办公家具', icon: 'fa fa-briefcase' },
      { id: 2, name: '电子设备', icon: 'fa fa-laptop' },
      { id: 3, name: '办公用品', icon: 'fa fa-pencil' },
      { id: 4, name: '清洁用品', icon: 'fa fa-shower' },
      { id: 5, name: '饮品', icon: 'fa fa-coffee' }
    ])
    
    const activeCategory = ref(0)
    const productsLoading = ref(false)
    
    // 示例商品数据
    const allProducts = ref<Product[]>([
      { id: 101, name: '办公椅', code: 'OC001', price: 299.2, image: 'chair.jpg', inventory: 50, categoryId: 1 },
      { id: 102, name: '办公桌', code: 'OD001', price: 699, image: 'desk.jpg', inventory: 30, categoryId: 1 },
      { id: 103, name: '文件柜', code: 'FC001', price: 499, image: 'cabinet.jpg', inventory: 20, categoryId: 1 },
      { id: 104, name: '笔记本电脑', code: 'LP001', price: 4999, image: 'laptop.jpg', inventory: 15, categoryId: 2 },
      { id: 105, name: '打印机', code: 'PR001', price: 1299, image: 'printer.jpg', inventory: 10, categoryId: 2 },
      { id: 106, name: '投影仪', code: 'PJ001', price: 2999, image: 'projector.jpg', inventory: 5, categoryId: 2 },
      { id: 107, name: '签字笔(10支装)', code: 'PN001', price: 25, image: 'pen.jpg', inventory: 100, categoryId: 3 },
      { id: 108, name: 'A4纸(500张)', code: 'PP001', price: 39, image: 'paper.jpg', inventory: 200, categoryId: 3 },
      { id: 109, name: '订书机', code: 'ST001', price: 15, image: 'stapler.jpg', inventory: 80, categoryId: 3 },
      { id: 110, name: '洗手液', code: 'CL001', price: 29, image: 'soap.jpg', inventory: 50, categoryId: 4 },
      { id: 111, name: '纸巾', code: 'TP001', price: 12, image: 'tissue.jpg', inventory: 100, categoryId: 4 },
      { id: 112, name: '矿泉水', code: 'WA001', price: 3, image: 'water.jpg', inventory: 200, categoryId: 5 },
      { id: 113, name: '咖啡', code: 'CF001', price: 15, image: 'coffee.jpg', inventory: 50, categoryId: 5 }
    ])
    
    // 过滤商品列表
    const filteredProducts = computed(() => {
      let result = allProducts.value
      
      // 按分类筛选
      if (activeCategory.value !== 0) {
        result = result.filter(product => product.categoryId === activeCategory.value)
      }
      
      // 按搜索词筛选
      if (searchQuery.value) {
        const query = searchQuery.value.toLowerCase()
        result = result.filter(product => 
          product.name.toLowerCase().includes(query) || 
          product.code.toLowerCase().includes(query)
        )
      }
      
      return result
    })
    
    // 购物车
    const cartItems = ref<CartItem[]>([])
    const customer = ref<Customer | null>(null)
    const discountAmount = ref(0)
    
    // 计算总金额
    const totalAmount = computed(() => {
      return cartItems.value.reduce((sum, item) => sum + (item.originalPrice * item.quantity), 0)
    })
    
    // 计算应付金额
    const payableAmount = computed(() => {
      return totalAmount.value - discountAmount.value
    })
    
    // 支付方式
    const paymentMethods = ref<PaymentMethod[]>([
      { id: 'cash', name: '现金', icon: 'fa fa-money' },
      { id: 'wechat', name: '微信', icon: 'fa fa-weixin' },
      { id: 'alipay', name: '支付宝', icon: 'fa fa-alipay' },
      { id: 'card', name: '银行卡', icon: 'fa fa-credit-card' }
    ])
    
    // 对话框控制
    const orderHistoryVisible = ref(false)
    const customerSelectVisible = ref(false)
    const paymentCompleteVisible = ref(false)
    const scanDialogVisible = ref(false)
    const shiftChangeVisible = ref(false)
    
    // 扫码相关
    const scanCode = ref('')
    const scanType = ref('product')
    
    // 优惠券数据（示例）
    const availableCoupons = ref<Coupon[]>([
      {
        code: 'FIRST10',
        type: 'percentage',
        value: 10,
        minAmount: 100,
        expiryDate: '2023-12-31',
        description: '满100元享9折'
      },
      {
        code: 'SAVE50',
        type: 'fixed',
        value: 50,
        minAmount: 200,
        expiryDate: '2023-12-31',
        description: '满200减50元'
      }
    ])
    
    // 交班数据
    const shiftStartTime = ref('2023-04-01 09:00:00')
    const shiftSummary = ref<ShiftSummary>({
      orderCount: 12,
      totalSales: 3856.5,
      totalDiscount: 352.8,
      totalRefund: 0,
      paymentBreakdown: {
        cash: 985.5,
        wechat: 1692,
        alipay: 879,
        card: 300
      }
    })
    
    // 交班表单数据
    const handoverForm = ref<HandoverForm>({
      type: 'shift',
      nextCashier: '',
      password: '',
      remark: ''
    })
    
    // 可选收银员列表
    const availableCashiers = ref<Cashier[]>([
      { id: 'cashier1', name: '李收银' },
      { id: 'cashier2', name: '王收银' },
      { id: 'cashier3', name: '张收银' },
      { id: 'manager1', name: '赵经理' }
    ])
    
    // 已完成订单信息
    const completedOrderInfo = ref<OrderInfo | null>(null)
    
    // 切换商品分类
    const changeCategory = (categoryId: number) => {
      activeCategory.value = categoryId
    }
    
    // 搜索商品
    const searchProduct = () => {
      // 实际应用中可能需要从后端搜索
      console.log('搜索商品:', searchQuery.value)
    }
    
    // 添加商品到购物车
    const addToCart = (product: Product) => {
      // 检查库存
      if (product.inventory <= 0) {
        ElMessage.warning('商品库存不足')
        return
      }
      
      // 检查购物车中是否已有该商品
      const existingItem = cartItems.value.find(item => item.productId === product.id)
      
      if (existingItem) {
        // 如果已存在，更新数量
        if (existingItem.quantity < product.inventory) {
          existingItem.quantity += 1
          ElMessage.success(`已添加 ${product.name} 到购物车`)
        } else {
          ElMessage.warning('商品库存不足')
        }
      } else {
        // 如果不存在，添加新项
        cartItems.value.push({
          id: Date.now(),
          productId: product.id,
          name: product.name,
          price: product.price,
          originalPrice: product.price,
          quantity: 1,
          image: product.image
        })
        ElMessage.success(`已添加 ${product.name} 到购物车`)
      }
    }
    
    // 更新购物车商品数量
    const updateCartItemQuantity = (itemId: number, quantity: number) => {
      const item = cartItems.value.find(item => item.id === itemId)
      if (item) {
        // 获取商品信息以检查库存
        const product = allProducts.value.find(p => p.id === item.productId)
        
        if (product && quantity <= product.inventory) {
          item.quantity = quantity
        } else {
          ElMessage.warning('商品库存不足')
        }
      }
    }
    
    // 移除购物车商品
    const removeCartItem = (itemId: number) => {
      cartItems.value = cartItems.value.filter(item => item.id !== itemId)
    }
    
    // 选择客户
    const selectCustomer = () => {
      customerSelectVisible.value = true
    }
    
    // 处理客户选择结果
    const onCustomerSelected = (selectedCustomer: Customer) => {
      customer.value = selectedCustomer
      
      // 根据客户等级应用折扣
      if (selectedCustomer.discount > 0) {
        applyDiscount(selectedCustomer.discount)
      }
    }
    
    // 应用折扣
    const applyDiscount = (discount: number) => {
      if (discount >= 0 && discount <= 100) {
        discountAmount.value = Math.floor((totalAmount.value * discount) / 100)
      }
    }
    
    // 应用抹零
    const applyRoundDown = () => {
      const currentAmount = payableAmount.value
      const roundedAmount = Math.floor(currentAmount)
      const difference = currentAmount - roundedAmount
      
      discountAmount.value += difference
      
      ElMessage.success(`已抹零 ¥${difference.toFixed(2)}`)
    }
    
    // 清空购物车
    const clearCart = () => {
      if (cartItems.value.length === 0) return
      
      ElMessageBox.confirm(
        '确定要清空购物车吗？',
        '确认信息',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).then(() => {
        cartItems.value = []
        customer.value = null
        discountAmount.value = 0
        ElMessage.success('购物车已清空')
      }).catch(() => {})
    }
    
    // 新建订单
    const newOrder = () => {
      if (cartItems.value.length > 0) {
        ElMessageBox.confirm(
          '当前购物车有商品，确定要开始新订单吗？',
          '确认信息',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        ).then(() => {
          clearCart()
        }).catch(() => {})
      }
    }
    
    // 显示订单历史
    const showOrderHistory = () => {
      orderHistoryVisible.value = true
    }
    
    // 加载历史订单
    const loadOrder = (orderNo: string) => {
      console.log('加载历史订单:', orderNo)
      // 实际应用中应从后端加载订单数据
    }
    
    // 完成支付
    const completePayment = (paymentData: any) => {
      if (cartItems.value.length === 0) {
        ElMessage.warning('购物车为空，无法完成支付')
        return
      }
      
      // 模拟生成订单号
      const orderNo = 'POS' + new Date().getTime().toString().slice(-8)
      
      // 模拟支付完成
      completedOrderInfo.value = {
        orderNo: orderNo,
        totalAmount: totalAmount.value,
        paidAmount: paymentData.amount,
        change: paymentData.amount - payableAmount.value,
        paymentMethod: paymentData.method,
        createTime: new Date().toLocaleString()
      }
      
      // 自动弹出支付完成对话框
      paymentCompleteVisible.value = true
      
      // 直接弹出打印提示
      setTimeout(() => {
        printReceipt()
      }, 500)
    }
    
    // 打印小票
    const printReceipt = () => {
      console.log('打印小票:', completedOrderInfo.value)
      // 实际应用中调用打印API
      ElMessage.success('小票打印中...')
    }
    
    // 开始新订单
    const startNewOrder = () => {
      cartItems.value = []
      customer.value = null
      discountAmount.value = 0
      completedOrderInfo.value = null
      paymentCompleteVisible.value = false
    }
    
    // 处理扫码按钮点击
    const handleScanCode = () => {
      scanCode.value = ''
      scanDialogVisible.value = true
    }
    
    // 获取扫码类型提示
    const getScanTypeTip = () => {
      const tipMap: Record<string, string> = {
        product: '请扫描商品条码，系统将自动添加到购物车',
        coupon: '请扫描优惠券二维码，系统将自动应用优惠',
        verification: '请扫描核销码，系统将验证其有效性'
      }
      return tipMap[scanType.value] || ''
    }
    
    // 处理扫码结果
    const processScanCode = () => {
      if (!scanCode.value) {
        ElMessage.warning('请输入扫描结果')
        return
      }
      
      switch (scanType.value) {
        case 'product':
          processProductCode()
          break
        case 'coupon':
          processCouponCode()
          break
        case 'verification':
          processVerificationCode()
          break
      }
      
      scanDialogVisible.value = false
    }
    
    // 处理商品条码
    const processProductCode = () => {
      // 实际应用中应从后端查询商品信息
      const product = allProducts.value.find(p => p.code === scanCode.value)
      
      if (product) {
        addToCart(product)
      } else {
        ElMessage.error('未找到商品: ' + scanCode.value)
      }
    }
    
    // 处理优惠券码
    const processCouponCode = () => {
      const coupon = availableCoupons.value.find(c => c.code === scanCode.value)
      
      if (coupon) {
        // 验证优惠券
        if (new Date(coupon.expiryDate) < new Date()) {
          ElMessage.error('优惠券已过期')
          return
        }
        
        if (totalAmount.value < coupon.minAmount) {
          ElMessage.error(`订单金额不满足优惠券使用条件，最低消费 ¥${coupon.minAmount}`)
          return
        }
        
        // 应用优惠
        let couponDiscount = 0
        
        if (coupon.type === 'fixed') {
          couponDiscount = coupon.value
        } else {
          couponDiscount = (totalAmount.value * coupon.value) / 100
        }
        
        discountAmount.value = couponDiscount
        
        ElMessage.success(`成功应用优惠券: ${coupon.description}`)
      } else {
        ElMessage.error('无效的优惠券码: ' + scanCode.value)
      }
    }
    
    // 处理核销码
    const processVerificationCode = () => {
      // 实际应用中应从后端验证核销码
      ElMessage.success('核销码验证成功: ' + scanCode.value)
    }
    
    // 显示交班对话框
    const showShiftChangeDialog = () => {
      shiftChangeVisible.value = true
    }
    
    // 获取当前时间
    const getCurrentTime = () => {
      return new Date().toLocaleString()
    }
    
    // 格式化价格
    const formatPrice = (price: number) => {
      return price.toFixed(2)
    }
    
    // 获取支付方式名称
    const getPaymentMethodName = (method: string) => {
      const methodMap: Record<string, string> = {
        cash: '现金',
        wechat: '微信',
        alipay: '支付宝',
        card: '银行卡'
      }
      return methodMap[method] || method
    }
    
    // 确认交班
    const confirmShiftChange = () => {
      // 表单验证
      if (!handoverForm.value.nextCashier && handoverForm.value.type === 'shift') {
        ElMessage.warning('请选择交接收银员')
        return
      }
      
      if (!handoverForm.value.password && handoverForm.value.type === 'daily') {
        ElMessage.warning('请输入管理员密码')
        return
      }
      
      // 确认对话框
      const confirmMessage = handoverForm.value.type === 'shift' 
        ? '确认完成交班操作？交班后将重新计算销售数据。' 
        : '确认完成日结操作？日结后将清空所有数据并生成日报表。'
      
      const confirmTitle = handoverForm.value.type === 'shift' ? '交班确认' : '日结确认'
      
      ElMessageBox.confirm(
        confirmMessage,
        confirmTitle,
        {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).then(() => {
        // 实际应用中应向后端提交交班数据
        const successMessage = handoverForm.value.type === 'shift' ? '交班完成' : '日结完成'
        ElMessage.success(successMessage)
        shiftChangeVisible.value = false
        
        // 重置交班数据
        shiftStartTime.value = getCurrentTime()
        shiftSummary.value = {
          orderCount: 0,
          totalSales: 0,
          totalDiscount: 0,
          totalRefund: 0,
          paymentBreakdown: {
            cash: 0,
            wechat: 0,
            alipay: 0,
            card: 0
          }
        }
        
        // 重置表单
        handoverForm.value = {
          type: 'shift',
          nextCashier: '',
          password: '',
          remark: ''
        }
      }).catch(() => {})
    }
    
    // 打印交班汇总
    const printShiftSummary = () => {
      // 实际应用中应调用打印API
      ElMessage.success('交班汇总打印中...')
    }
    
    // 处理扫描优惠券
    const handleScanCoupon = () => {
      scanType.value = 'coupon'
      scanCode.value = ''
      scanDialogVisible.value = true
    }
    
    // 显示手动打折对话框
    const showManualDiscountDialog = () => {
      ElMessageBox.prompt(
        '请输入折扣率（%）',
        '手动打折',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          inputType: 'text',
          inputValue: customer.value ? customer.value.discount.toString() : '0',
          inputValidator: (value) => {
            const num = parseFloat(value)
            return !isNaN(num) && num >= 0 && num <= 100
          },
          inputErrorMessage: '请输入0-100之间的数值'
        }
      ).then(({ value }) => {
        const discountRate = parseFloat(value)
        applyDiscount(discountRate)
        
        ElMessage.success(`已应用${discountRate}%折扣`)
      }).catch(() => {})
    }
    
    // 初始化
    onMounted(() => {
      // 实际应用中可能需要加载商品数据、分类等
      productsLoading.value = true
      
      // 模拟加载数据
      setTimeout(() => {
        productsLoading.value = false
      }, 500)
    })
    
    return {
      // 状态
      searchQuery,
      selectedStore,
      cashierName,
      stores,
      categories,
      activeCategory,
      productsLoading,
      filteredProducts,
      cartItems,
      customer,
      totalAmount,
      discountAmount,
      payableAmount,
      paymentMethods,
      orderHistoryVisible,
      customerSelectVisible,
      paymentCompleteVisible,
      scanDialogVisible,
      scanCode,
      scanType,
      shiftChangeVisible,
      shiftStartTime,
      shiftSummary,
      handoverForm,
      availableCashiers,
      completedOrderInfo,
      
      // 方法
      changeCategory,
      searchProduct,
      addToCart,
      updateCartItemQuantity,
      removeCartItem,
      selectCustomer,
      onCustomerSelected,
      applyDiscount,
      applyRoundDown,
      clearCart,
      newOrder,
      showOrderHistory,
      loadOrder,
      completePayment,
      printReceipt,
      startNewOrder,
      handleScanCode,
      getScanTypeTip,
      processScanCode,
      showShiftChangeDialog,
      getCurrentTime,
      formatPrice,
      getPaymentMethodName,
      confirmShiftChange,
      printShiftSummary,
      handleScanCoupon,
      showManualDiscountDialog
    }
  }
})
</script>

<style scoped lang="scss">
.pos-container {
  display: flex;
  flex-direction: column;
  height: 90vh;
  background-color: #f5f7fa;
  overflow: hidden;
  
  .pos-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 8px 15px;
    background: linear-gradient(135deg, #2c3e50, #3498db);
    color: white;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
    height: 60px;
    
    .logo-section {
      display: flex;
      align-items: center;
      font-size: 20px;
      font-weight: 500;
      
      .logo-image {
        height: 36px;
        margin-right: 10px;
      }
      
      .logo-text {
        background: -webkit-linear-gradient(#ffffff, #d1d1d1);
        -webkit-background-clip: text;
        -webkit-text-fill-color: transparent;
        text-shadow: 0 1px 2px rgba(0,0,0,0.2);
      }
    }
    
    .action-section {
      display: flex;
      align-items: center;
      gap: 12px;
      
      .search-input {
        width: 220px;
      }
      
      .store-select {
        width: 110px;
      }
      
      .cashier-info {
        display: flex;
        align-items: center;
        margin-left: 5px;
        background-color: rgba(255, 255, 255, 0.2);
        padding: 4px 8px;
        border-radius: 4px;
        font-size: 14px;
        
        i {
          margin-right: 5px;
        }
      }
    }
  }
  
  .pos-content {
    display: flex;
    flex: 1;
    height: calc(100vh - 60px);
    overflow: hidden;
    
    .pos-left-panel {
      width: 65%;
      display: flex;
      flex-direction: column;
      overflow: hidden;
      border-right: 1px solid #e6e6e6;
    }
    
    .pos-right-panel {
      width: 35%;
      display: flex;
      flex-direction: column;
      overflow: hidden;
      background-color: white;
    }
  }
}

.scan-dialog-content {
  .scan-type-tabs {
    margin-bottom: 20px;
    text-align: center;
  }
  
  .scan-input-area {
    .scan-tip {
      margin-top: 15px;
      text-align: center;
      color: #909399;
      font-size: 14px;
      
      i {
        margin-right: 5px;
      }
    }
  }
}

.shift-change-content {
  .shift-info {
    .shift-header {
      display: flex;
      justify-content: space-between;
      margin-bottom: 15px;
      background-color: #f0f9eb;
      padding: 12px;
      border-radius: 4px;
      
      .cashier-name {
        font-size: 16px;
        font-weight: 500;
        color: #67c23a;
      }
      
      .shift-time {
        font-size: 14px;
        color: #606266;
      }
    }
    
    .shift-summary {
      .summary-item {
        display: flex;
        justify-content: space-between;
        margin-bottom: 10px;
        
        .item-label {
          color: #606266;
        }
        
        .item-value {
          font-weight: 500;
        }
      }
      
      .payment-breakdown {
        margin-top: 15px;
        background-color: #f5f7fa;
        padding: 12px;
        border-radius: 4px;
        
        .breakdown-title {
          font-weight: 500;
          margin-bottom: 10px;
          color: #409EFF;
          border-bottom: 1px dashed #dcdfe6;
          padding-bottom: 5px;
        }
        
        .breakdown-item {
          display: flex;
          justify-content: space-between;
          margin-bottom: 8px;
          padding-left: 15px;
          
          .item-label {
            color: #606266;
          }
        }
      }
    }
    
    .handover-info {
      margin-top: 15px;
      
      .handover-title {
        font-weight: 500;
        margin-bottom: 10px;
        color: #409EFF;
        border-bottom: 1px dashed #dcdfe6;
        padding-bottom: 5px;
      }
      
      .handover-form {
        background-color: #f5f7fa;
        padding: 12px;
        border-radius: 4px;
        
        .el-form-item {
          margin-bottom: 10px;
        }
      }
    }
  }
  
  .shift-actions {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
    gap: 10px;
  }
}
</style> 